package org.example.service;

import org.example.dao.OrderDao;
import org.example.dao.ProductDao;
import org.example.pojo.Order;
import org.example.pojo.Product;

import java.util.List;

public class OrderService {
    private final OrderDao orderDao = new OrderDao();
    private final ProductDao productDao = new ProductDao();

    // 根据用户 ID 获取订单列表
    public List<Order> getOrdersByUserId(int userId) {
        return orderDao.getOrdersByUserId(userId);
    }

    // 下单
    public boolean placeOrder(int userId, int productId, int quantity) {
        Product product = productDao.getProductById(productId);
        if (product == null) {
            System.err.println("商品不存在！");
            return false;
        }
        if (product.getStock() < quantity) {
            System.err.println("库存不足！");
            return false;
        }

        // 更新库存
        boolean isStockUpdated = productDao.updateStock(productId, product.getStock() - quantity);
        if (!isStockUpdated) {
            System.err.println("库存更新失败！");
            return false;
        }

        // 创建订单
        boolean isOrderCreated = orderDao.insertOrder(userId, productId, quantity);
        if (!isOrderCreated) {
            productDao.updateStock(productId, product.getStock());
            System.err.println("订单插入失败，库存扣减回滚！");
            return false;
        }

        return true;
    }

    // 删除订单并恢复库存
    public boolean deleteOrderAndRestoreStock(int orderId) {
        Order order = orderDao.getOrderById(orderId);
        if (order == null) {
            System.err.println("订单不存在！");
            return false;
        }

        int productId = order.getProductId();
        int quantity = order.getQuantity();

        // 恢复库存
        Product product = productDao.getProductById(productId);
        if (product == null) {
            System.err.println("商品不存在，无法恢复库存！");
            return false;
        }

        boolean isStockRestored = productDao.updateStock(productId, product.getStock() + quantity);
        if (!isStockRestored) {
            System.err.println("恢复库存失败！");
            return false;
        }

        // 删除订单
        boolean isOrderDeleted = orderDao.deleteOrderById(orderId);
        if (!isOrderDeleted) {
            productDao.updateStock(productId, product.getStock() - quantity); // 回滚库存恢复
            System.err.println("订单删除失败，库存恢复回滚！");
            return false;
        }

        return true;
    }
}
